package com.example.demo.leetcode.top100;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname _68寻找两个正序数组的中位数
 * @description
 * @date 2023/06/24 9:57
 * <p>
 * ******************************************************
 */
public class _68寻找两个正序数组的中位数 {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int m = nums1.length;
        int n = nums2.length;
        // 是否是奇数个
        boolean isOdd = (m + n) % 2 == 1;
        // 5/2 = 2  OR  4/2=2
        // 取值3         取值2、3
        int mid = (m + n) / 2;
        int index1 = 0;
        int index2 = 0;
        int midVal1 = 0;
        int midVal2 = 0;
        while (mid >= 0) {
            mid--;
            // 为true情况
            // 1、下标都在范围内且nums1[index1] < nums2[index2]
            // 2、num2下标超界
            // 说明：实际不可能两者下标都超界
            if ((index1 < m && index2 < n && nums1[index1] < nums2[index2])
                    || (index2 >= n)) {
                if (mid == 0) {
                    midVal1 = nums1[index1];
                }
                if (mid < 0) {
                    midVal2 = nums1[index1];
                }
                index1++;
            } else {
                if (mid == 0) {
                    midVal1 = nums2[index2];
                }
                if (mid < 0) {
                    midVal2 = nums2[index2];
                }
                index2++;
            }
        }
        return isOdd ? (double) midVal2 : (double) (midVal1 + midVal2) / 2;
    }
}
